//
//  RecommendCyleView.swift
//  CWLiving
//
//  Created by 方正刚 on 2017/7/10.
//  Copyright © 2017年 方正刚. All rights reserved.
//

import UIKit


private let CYCLECELL_ID = "CYCLECELL_ID"

private let Pagacontol_HEIGHT: CGFloat = 30

private let TIME_INTERVAL = 3.0

class RecommendCyleView: UIView {

    var cycleTimer: Timer?
    
    var cycleModels: [CycleModel]? {
        didSet {
        
            collectionView.reloadData()
            
            let indexPath = NSIndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0) as IndexPath
            
            collectionView.scrollToItem(at: indexPath , at: .left, animated: false)
            
            //启动定时器
            removeTimer()
            startTimer()
        }
    }
    
    
    /// 懒加载collectionView
    lazy var collectionView: UICollectionView = { [unowned self] in
    
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = self.bounds.size
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.bounces = false
        collectionView.isPagingEnabled = true
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(CollectionCycleCell.self, forCellWithReuseIdentifier: CYCLECELL_ID)
    
        return collectionView
    }()

    
    /// 懒加载pageControl
    lazy var pageControl: UIPageControl = {
    
    let pageControl = UIPageControl(frame: CGRect(x: 0, y: self.bounds.size.height - Pagacontol_HEIGHT, width: self.bounds.size.width, height: Pagacontol_HEIGHT))
        pageControl.numberOfPages = 6
        pageControl.pageIndicatorTintColor = UIColor.white
        pageControl.currentPageIndicatorTintColor = UIColor.orange
        pageControl.isEnabled = false
        
        return pageControl
    }()
    
    
    /// 轮播点的背景视图
    lazy var pageBgView: UIView = {
    
        let pageBgView = UIView(frame: CGRect(x: 0, y: self.bounds.size.height - Pagacontol_HEIGHT, width: self.bounds.size.width, height: Pagacontol_HEIGHT))
            pageBgView.backgroundColor = UIColor.black
            pageBgView.alpha = 0.5
        
        return pageBgView
    }()
    
     override init(frame: CGRect) {
        super.init(frame: frame)
        
       setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


// MARK: - 设置UI
extension RecommendCyleView {
    
    func setupUI() {
      
      setupCollectionView()
        
      setupPageControl()
    }
    
    /// 布局CollectionView
    func setupCollectionView() {
      
        addSubview(collectionView)
    }
    
    
    /// 布局PageControl
    func setupPageControl() {
        
        addSubview(pageBgView)
        addSubview(pageControl)
    }
    
    
}

// MARK: - UICollectionViewDataSource 数据源协议
extension RecommendCyleView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (cycleModels?.count ?? 0) * 1000
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CYCLECELL_ID, for: indexPath) as! CollectionCycleCell
        
        cell.cycleModel = cycleModels?[indexPath.item % cycleModels!.count]
        
        return cell
        
        
    }
    
}


// MARK: - UICollectionViewDelegate 代理协议
extension RecommendCyleView: UICollectionViewDelegate {
  
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
        
        pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        removeTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        startTimer()
    }
}


// MARK: - 操作定时器的方法
extension RecommendCyleView {
    
    func startTimer() {
        cycleTimer = Timer(timeInterval: TIME_INTERVAL, target: self, selector: #selector(beginScroll), userInfo: nil, repeats: true)
        RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes)
    }
    
    func removeTimer() {
        cycleTimer?.invalidate() // 从运行循环中移除
        cycleTimer = nil
    }
    
    
    func beginScroll() {
        
        let collectionViewOffsetX = collectionView.contentOffset.x
        
        let offsetx = collectionViewOffsetX + bounds.width
        
        collectionView.setContentOffset(CGPoint(x: offsetx, y: 0), animated: true)
    }
    
}








